<template>
  <transition enter-active-class="slideInUp faster animated" leave-active-class="slideOutDown faster animated">
    <div class="photoModule" v-show="isShowAni">
      <div class="photoBox publicVCenter">
        <img src="@/assets/image/hdBar/photoBapinTitle.png" class="titleImg" />
        <div class="note publicHvCenter">您发送的图片会展示在大屏幕上，快来试试吧！</div>
        <div class="sizeWrap">
          <div
            class="item publicHvCenter"
            v-for="item in photoTypeList_display"
            :key="item.id"
            :class="[item.size, { active: currentPhotoType === item.giftId }]"
            v-tap="{ methods: choosePhotoType, giftId: item.giftId }"
          >
            <div class="price publicHvCenter" v-if="!item.isFree">
              {{ item.price }}<img src="@/assets/image/hdBar/diamond.png" class="unit" />
            </div>
            <div class="price publicHvCenter" v-if="item.isFree">免费</div>
            <div class="size publicHvCenter">{{ item.name }}</div>
            <div class="time">{{ item.time }}s</div>
          </div>
        </div>
        <div class="txtWrap publicHCenter">
          <textarea
            v-model="content"
            :maxlength="canCustomizeInput ? 20 : 0"
            ref="text"
            cols="30"
            rows="10"
            placeholder="输入内容(20字以内)"
            v-on:blur="handleBlur"
          ></textarea>
          <div class="ylBtn publicHvCenter" v-tap="{ methods: ganerateRandomWish }">语录</div>
          <div class="photoWrap publicHvCenter">
            <div class="addPlus publicHvCenter" v-show="!hasUpload"><img src="@/assets/image/hdBar/addIcon.png" class="addIcon" /></div>
            <img :src="previewImg" class="previewImg" v-show="hasUpload" v-tap="{ methods: showPreview }" />
            <input ref="fileinput" accept="image/*" type="file" class="file" @change="change" v-show="!hasUpload" />
            <div class="uploadNum">({{hasUpload?1:0}}/1)</div>
          </div>
        </div>
        <div class="btnWrap publicHvCenter" v-tap="{ methods: sendPhoto }">发送</div>
      </div>
      <div class="previewBox publicVCenter" v-if="previewShow">
        <img :src="previewImg" />
        <div class="btnGroup">
          <div v-tap="{ methods: cancelPreview }">取消</div>
          <div v-tap="{ methods: confirmPreview }">确定</div>
        </div>
      </div>
    </div>
  </transition>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
import { timeoutTask, generateRandom } from '@/utils/index';
import { uploadPhoto, sendPhotoGift } from '@/api/index/index';
import { sendPhotoGiftMessage } from '@/api/chat/index';
import { POPUP_MODULE, QUICKWISH } from '@/assets/constant/index';

const quickWishLen = QUICKWISH.length;

export default {
  name: 'photoPopup',
  computed: {
    ...mapState({
      previewImg: (state) => state.app.previewImg,
      photoTypeList: (state) => state.live.photoTypeList,
      currentPhotoType: (state) => state.app.currentPhotoType,
      money: (state) => state.user.money,
      freeSendGift: (state) => state.user.freeSendGift,
      isFreeSendPhoto: (state) => state.live.isFreeSendPhoto,
      canCustomizeInput: (state) => state.app.canCustomizeInput,
    }),
    photoTypeList_display() {
      let tmpList;
      if (this.isFreeSendPhoto) {
        tmpList = this.photoTypeList.map((item) => {
          return {
            ...item,
            isFree: item.size === 'small',
          };
        });
      } else {
        tmpList = this.photoTypeList;
      }
      return tmpList;
    },
  },
  watch: {
    canCustomizeInput(value) {
      if (!value) {
        this.content = '';
      }
    },
  },
  created() {},
  mounted() {
    // 执行弹出动画
    this.showAniStart();
  },
  data() {
    return {
      isShowAni: false, // 控制bapin box弹出动画
      hasUpload: false,
      previewShow: false,
      content: '',
    };
  },
  methods: {
    ...mapMutations({
      setPreviewImg: 'app/setPreviewImg',
      resetPreviewImg: 'app/resetPreviewImg',
      setCurrentPhotoType: 'app/setCurrentPhotoType',
      setUserInfo: 'user/setUserInfo',
      togglePopup: 'app/togglePopup',
      setOrigin: 'app/setOrigin',
    }),
    handleBlur() {
      window.scrollTo(0, -document.documentElement.clientHeight);
    },
    showAniStart() {
      timeoutTask(() => {
        this.isShowAni = true;
      }, 100);
    },
    hideAniStart() {
      this.isShowAni = false;
    },
    ganerateRandomWish() {
      this.content = QUICKWISH[generateRandom(0, quickWishLen)];
    },
    change(e) {
      try {
        this.$loading('图片加载中...');
        const freader = new FileReader();
        const file = e.target.files[0];
        // const fixOrientation = require('fix-orientation');

        freader.onload = (ev) => {
          const url = ev.target.result;
          this.setPreviewImg(url);
          this.previewShow = true;
          this.hasUpload = true;
          this.$loading.close();
          // fixOrientation(
          //   url,
          //   {
          //     image: true,
          //   },
          //   (fixedImg) => {
          //     this.setPreviewImg(fixedImg);
          //     this.previewShow = true;
          //     this.hasUpload = true;
          //     this.$loading.close();
          //   }
          // );
        };

        freader.onerror = () => {
          this.$loading.close();
          this.$toast.center('图片加载失败');
        };

        freader.readAsDataURL(file); // 读取照片
      } catch (err) {
        this.$loading.close();
      }
    },
    showPreview() {
      this.previewShow = true;
    },
    cancelPreview() {
      this.hasUpload = false;
      this.resetPreviewImg();
      this.$refs.fileinput.value = '';
      this.previewShow = false;
    },
    confirmPreview() {
      this.previewShow = false;
    },
    choosePhotoType(p) {
      this.setCurrentPhotoType(p.giftId);
    },
    sendPhoto() {
      // 发送前的验证
      if (!this.validateSend()) {
        return;
      }
      this.$loading('发送祝福中...');
      this.uploadPhoto().then((res1) => {
        console.log('***上传照片***');
        console.log(res1);
        this.setPreviewImg(res1.filePath);
        return sendPhotoGift(this.content, this.previewImg)
          .then((res2) => {
            // 更新 用户余额
            this.setUserInfo({
              money: res2.result.balance,
            });
            return this.sendBroadcast(); // 发送礼物的广播
          })
          .then((res3) => {
            console.log(res3);
            this.$loading.close();
            this.$toast.center('发送成功!');
            // 清空数据
            this.hasUpload = false;
            this.content = '';
            this.resetPreviewImg();
            this.togglePopup();
            this.$refs.text.blur();
          })
          .catch((err) => {
            console.log(err);
            this.$loading.close();
            this.$toast.center('发送失败!');
          });
      });
    },
    validateSend() {
      let flag = true;
      const choosedPhotoType = this.photoTypeList_display.find((item) => item.giftId === this.currentPhotoType);
      if (!this.content) {
        flag = false;
        this.$toast.center('请输入您的祝福!');
      } else if (!this.previewImg) {
        flag = false;
        this.$toast.center('请选择您发送的图片');
      } else if (this.freeSendGift) {
        // 免费发礼物
        flag = true;
      } else if (choosedPhotoType.isFree) {
        // 本场免费发照片
        flag = true;
      } else if (choosedPhotoType.price > this.money) {
        this.$toast.center('余额不足,请充值!');
        flag = false;
        this.setOrigin('sendPhoto');
        this.togglePopup();
        timeoutTask(() => {
          this.togglePopup(POPUP_MODULE.rechargeModule.key);
        }, 200);
      }
      return flag;
    },
    uploadPhoto() {
      const formData = new FormData();
      const arr = this.previewImg.split(',');
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      /* eslint-disable */
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      const file = new File([u8arr], 'photo');
      formData.append('file', file);
      formData.append('prefix', 'love');
      return uploadPhoto(formData);
    },
    sendBroadcast() {
      return sendPhotoGiftMessage(this.content, this.previewImg);
    },
  },
};
</script>
<style lang="less" scoped>
.photoModule {
  position: absolute;
  width: 100%;
  bottom: 0;
  .photoBox {
    width: 750px;
    height: 824px;
    background: #170d41;
    flex-direction: column;
    .titleImg {
      width: 342px;
      height: 72px;
    }
    .note {
      margin-top: 32px;
      background: #4e4584;
      border-radius: 32px;
      width: 570px;
      height: 64px;
      font-size: 24px;
      font-weight: 400;
      color: #c2baf5;
    }
    .sizeWrap {
      width: 100%;
      margin-top: 74px;
      display: flex;
      justify-content: space-around;
      .item {
        width: 148px;
        height: 120px;
        border-radius: 8px;
        position: relative;
        flex-direction: column;
        padding-top: 12px;
        .price {
          width: 108px;
          height: 40px;
          background-image: url('../../assets/image/hdBar/priceDg.png');
          background-size: 100% 100%;
          position: absolute;
          top: -27px;
          right: 0px;
          font-size: 24px;
          color: #fff;
          letter-spacing: 1px;
          .unit {
            width: 20px;
            height: 16px;
            margin-left: 4px;
          }
        }
        .size {
          color: #ffffff;
          border-radius: 50%;
          border: solid 1px #ffffff;
        }
        .time {
          font-size: 20px;
          color: #ffffff;
          margin-top: 14px;
        }
        &.small {
          background: linear-gradient(276deg, #71b3ff 0%, #2c82e4 100%);
          .size {
            width: 40px;
            height: 40px;
            font-size: 20px;
          }
          &.active {
            box-shadow: 0px 0px 50px #2c82e4;
          }
        }
        &.mid {
          background: linear-gradient(276deg, #c571ff 0%, #e42cd5 100%);
          .size {
            width: 48px;
            height: 48px;
            font-size: 24px;
          }
          &.active {
            box-shadow: 0px 0px 50px #e42cd5;
          }
        }
        &.large {
          background: linear-gradient(276deg, #ff7171 0%, #e42c2c 100%);
          .size {
            width: 56px;
            height: 56px;
            font-size: 28px;
          }
          &.active {
            box-shadow: 0px 0px 50px #e42c2c;
          }
        }
        &.ba {
          background: linear-gradient(300deg, #c76bfb 0%, #ea1775 100%);
          .size {
            width: 60px;
            height: 60px;
            font-size: 36px;
          }
          &.active {
            box-shadow: 0px 0px 50px #ea1775;
          }
        }
      }
    }
    .txtWrap {
      margin-top: 48px;
      position: relative;
      textarea {
        width: 710px;
        height: 184px;
        border: 2px solid;
        border-image: linear-gradient(104deg, #45f6fe 0%, #c026ed 100%) 1 1;
        font-size: 24px;
        padding: 18px 32px;
        padding-right: 132px;
        color: #fff;
        outline: none;
        box-sizing: border-box;
        background-color: transparent;
        &::placeholder {
          font-size: 28px;
          color: #756ea1;
        }
      }
      .ylBtn {
        width: 88px;
        height: 48px;
        background: #231f44;
        border-radius: 10px;
        font-size: 28px;
        font-weight: 400;
        color: #c2baf5;
        position: absolute;
        top: 32px;
        right: 48px;
      }
      .photoWrap {
        width: 78px;
        height: 78px;
        position: absolute;
        bottom: 23px;
        left: 31px;
        border-radius: 50%;
        .addPlus {
          width: 78px;
          height: 78px;
          background-size: 100% 100%;
          background-image: url('../../assets/image/hdBar/addBorder.png');
          .addIcon {
            width: 28px;
            height: 28px;
          }
        }
        .previewImg {
          position: absolute;
          width: 90px;
          height: 90px;
          bottom: 0;
          right: 0;
        }
        .file {
          position: absolute;
          width: 60px;
          height: 60px;
          opacity: 0;
        }
        .uploadNum {
          font-size: 28px;
          font-weight: 400;
          color: #3b394f;
          position: absolute;
          bottom: 0;
          left: 83px;
        }
      }
    }
    .btnWrap {
      width: 400px;
      height: 92px;
      background: linear-gradient(90deg, #6c47ff, #ff68f9 100%);
      border-radius: 8px;
      margin-top: 48px;
      color: #ffffff;
      font-size: 32px;
      font-weight: 400;
    }
  }
  .previewBox {
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    background: #000;
    img {
      width: 100vw;
    }
    .btnGroup {
      width: 100%;
      height: 10vh;
      background-color: #000;
      display: flex;
      position: absolute;
      left: 0;
      bottom: 0;
      div {
        color: #fff;
        width: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
}
</style>
